package com.otaliastudios.cameraview.demo

import android.content.Intent
import android.graphics.Color
import android.graphics.Point
import android.graphics.SurfaceTexture
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.ResultReceiver
import android.view.Surface
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.otaliastudios.cameraview.*
import com.otaliastudios.cameraview.demo.databinding.ActivityMainBinding
import com.otaliastudios.cameraview.engine.RtspEngine
import com.otaliastudios.cameraview.entity.MarkGravity
import com.otaliastudios.cameraview.entity.WarterMarkBean
import com.otaliastudios.cameraview.livedata.MarkMapLiveData
import com.otaliastudios.cameraview.livedata.RecordPauseLiveData
import com.otaliastudios.cameraview.preview.CameraPreview
import com.otaliastudios.cameraview.size.Size
import org.easydarwin.video.Client
import org.easydarwin.video.EasyPlayerClient
import org.opencv.android.OpenCVLoader
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    val KEY1 = "EasyPlayer is free!"
    var url = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4"
    private var strUrl1 = "rtsp://admin:srod@0711@192.168.16.100:554/h265/ch1/main/av_stream"
    lateinit var cameraView: CameraView
    lateinit var streamRender: EasyPlayerClient
    lateinit var binding: ActivityMainBinding
    val mResultReceiver: ResultReceiver = object : ResultReceiver(Handler()) {
        override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
            super.onReceiveResult(resultCode, resultData)
            if (resultData != null) {
                val videoDecodeType = resultData.getInt(EasyPlayerClient.KEY_VIDEO_DECODE_TYPE, 0)
                LogPlus.w("视频解码方式:" + if (videoDecodeType == 0) "软解码" else "硬解码")
            }
            when (resultCode) {
                EasyPlayerClient.RESULT_VIDEO_SIZE -> {
                    val size: Size = cameraView.cameraEngine.mSizes[0]
                    val width = resultData?.getInt(EasyPlayerClient.EXTRA_VIDEO_WIDTH) ?: 1920
                    val height = resultData?.getInt(EasyPlayerClient.EXTRA_VIDEO_HEIGHT) ?: 1080
                    val b: Boolean = cameraView.cameraEngine.screenOrientation()
                    val widthX = if (b) width else height
                    val heightX = if (b) height else width
                    if (size.width != widthX || size.height != heightX) {
                        LogPlus.w("shipin尺寸===>$width---->$height")
                        val newSize =  Size(width, height)
                        cameraView.cameraEngine.mSizes[0] = newSize
                        // onPreviewStreamSizeChanged();

                    }
                }
                EasyPlayerClient.RESULT_RECONNECT -> {}
                EasyPlayerClient.RESULT_EVENT -> {
                    val errorcode = resultData?.getInt("errorcode")
                    val msg = resultData?.getString("event-msg")
                    val runtime: Exception = RuntimeException(msg)
                    LogPlus.w(
                        String.format(
                            "[%s]\t%s\n",
                            SimpleDateFormat("HH:mm:ss").format(Date()),
                            msg
                        ), "----->$errorcode"
                    )
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        OpenCVLoader.initDebug()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        cameraView = findViewById<CameraView>(R.id.cameraView)
        cameraView.setLifecycleOwner(this)
        binding.markview.setLifecycleOwner(this)
        binding.record.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) cameraView.takeVideoSnapshot(saveVideoPath) else cameraView.stopVideo()
        }
        binding.recordPause.setOnCheckedChangeListener { buttonView, isChecked ->
            RecordPauseLiveData.get().value = isChecked
        }

        cameraView.cameraEngine.setRtspEngineListener(object : RtspEngine.RtspEngineListener {
            override fun onStartEngine() {
                streamRender = EasyPlayerClient(this@MainActivity, KEY1, null, mResultReceiver)
            }

            override fun onStartBind(preview: CameraPreview<*, *>): Size {
                streamRender.setSurface(Surface(preview.output as SurfaceTexture))
                return Size(1920, 1088)
            }

            override fun onStartPreview() {
                try {
                    streamRender.start(
                        strUrl1,
                        0,
                        Client.EASY_SDK_VIDEO_FRAME_FLAG or Client.EASY_SDK_AUDIO_FRAME_FLAG,
                        "",
                        ""
                    )
                } catch (e: Exception) {
                    e.printStackTrace()
                    Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
                }
            }

            override fun onStopPreview() {
                streamRender.stopCamera()
            }

            override fun onStopEngine() {

            }

        })
        cameraView.cameraEngine.videoSize = Size(1080, 720)
        findViewById<Button>(R.id.takePhoto).setOnClickListener {
            startActivity(
                Intent(
                    this,
                    CameraActivity::class.java
                )
            )
        }

        cameraView.addCameraListener(object : CameraListener() {
            override fun onPictureTaken(result: PictureResult) {
                super.onPictureTaken(result)
                LogPlus.w("图片尺寸===>${result.size}--->角度-->${result.rotation}")
                result.toBitmap {
                    findViewById<ImageView>(R.id.photoImage).setImageBitmap(it)

                }
            }

            override fun onVideoRecordingStart() {
                super.onVideoRecordingStart()
                LogPlus.e("我录制开始了")
            }

            override fun onVideoTaken(result: VideoResult) {
                super.onVideoTaken(result)
                LogPlus.e("我录制完成===>${result.file}")
            }
        })


        val str = "你好,乐乐 [带我去嫖]逗比-->王中王--->[你妹的]===东方今典减肥的[人渣蛋蛋]--==叫对方答复绝对是[你妹是傻逼]"
        val replace = str.replace("\\[[^\\]]*\\]".toRegex(), "")
        LogPlus.w("原始数据=$str")
        LogPlus.w("变化数据=$replace")


        var value = MarkMapLiveData.get().value
        var size = Size(1700, 956)
        value["ooo"] = WarterMarkBean("ooo", Point(32, 32), null, "我来了,我日了狗啊", Color.WHITE)
        value["TTT"] = WarterMarkBean("TTT", Point(32, 32 * 2), null, "狗中大长腿柯基", Color.WHITE)
        value["UUU"] = WarterMarkBean(
            "UUU",
            Point(size!!.width, 32 * 3),
            null,
            "柯基是大长腿",
            Color.WHITE,
            32F,
            MarkGravity.RIGHT, -180
        )

        cameraView.postDelayed({
            value.clear()
            value["UUU"] = WarterMarkBean(
                "UUU",
                Point(size!!.width, 32 * 8),
                null,
                "柯基是大长腿",
                Color.WHITE,
                32F,
                MarkGravity.RIGHT, -20
            )
        }, 6000)


        binding.mjpegBtn.setOnClickListener {
            startActivity(Intent(this, MjpegActivity::class.java))
        }
    }

    val saveVideoPath: File
        get() {
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            val time = format.format(Date())
            val file =
                File(Environment.getExternalStorageDirectory().path + "/test/live_save_video-" + time + ".avi")
            file.parentFile.mkdirs()
            return file
        }
}